package apollo

import (
	"github.com/apolloconfig/agollo/v4"
	"github.com/apolloconfig/agollo/v4/agcache"
	"github.com/apolloconfig/agollo/v4/env/config"
	"github.com/reiver/go-telnet"
	"strconv"
)

// telnetCheck agollo不晓得为什么非要这么一下
func telnetCheck(addr string) error {
	if conn, err := telnet.DialTo(addr); err != nil {
		return err
	} else {
		conn.Close()
		return nil
	}
}

// 获取apollo client
func getAgolloClient(c *config.AppConfig) (agollo.Client, error) {
	client, err := agollo.StartWithConfig(func() (*config.AppConfig, error) {
		return c, nil
	})
	return client, err
}

// read string from agcache.CacheInterface
func readString(cache agcache.CacheInterface, key string) string {
	value, e := cache.Get(key)
	if e != nil {
		return ""
	}
	switch value.(type) {
	case int:
		return strconv.Itoa(value.(int))
	case string:
		return value.(string)
	default:
		return ""
	}
}

// read int from agcache.CacheInterface
func readInt(cache agcache.CacheInterface, key string) int {
	value, e := cache.Get(key)
	if e != nil {
		return 0
	}
	switch value.(type) {
	case int:
		return value.(int)
	case string:
		n, _ := strconv.Atoi(value.(string))
		return n
	default:
		return 0
	}
}
